package com.jp.knowledge.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.bigkoo.pickerview.TimePickerView;
import com.bigkoo.pickerview.listener.CustomListener;
import com.google.gson.JsonObject;
import com.jiayen.cache.FileCacheManager;
import com.jiayen.util.ToasUtil;
import com.jp.knowledge.R;
import com.jp.knowledge.activity.BaseFragment;
import com.jp.knowledge.adapter.FragMentAdapter;
import com.jp.knowledge.broad.LocalBroadCast;
import com.jp.knowledge.db.DBHelper;
import com.jp.knowledge.dialog.HeadLineDailog;
import com.jp.knowledge.http.HttpHelper;
import com.jp.knowledge.logic.PositionKnowlegeDataLogic;
import com.jp.knowledge.model.HeadLine;
import com.jp.knowledge.model.IModel;
import com.jp.knowledge.model.PositionKnowlegeMode;
import com.jp.knowledge.model.TabModel;
import com.jp.knowledge.util.ResultSubscriber;
import com.jp.knowledge.util.SharedUtil;
import com.jp.knowledge.util.TabDateUtil;
import com.jp.knowledge.util.TimeUtil;
import com.jp.knowledge.view.TabView;

import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

import static android.content.Intent.ACTION_DATE_CHANGED;


/***
 * 知识餐
 *2017/06/01
 * create by  jiayen
 */
public class KnowledgeFragment extends BaseFragment implements ResultSubscriber.OnResultListener, View.OnClickListener {

    private List<String> tabNames = new ArrayList<>();
    private List<Fragment> fragments = new ArrayList<>();
    private FragMentAdapter adpter;
    protected List<HeadLine> headLines;
    private List<TabModel>  tabModels;

    @ViewInject(R.id.tab_view)
    private TabView tabView;


    private View  mView;
    @ViewInject(R.id.view_pager)
    private ViewPager viewPage;

    private  HeadLine curHeadLine;
    private HeadLineDailog  headLineDailog;
    private TimePickerView timerPicker;

    //使用本地广播来刷新数据
    private LocalBroadcastManager localBroadcastManager;

    private LocalBroadCast localBroadCast;
    private BroadcastReceiver dataChangeBroadCast;
    private int lastPosition;
    private PositionKnowlegeDataLogic  logic;

    private FileCacheManager  fileCacheManager;

    protected List<PositionKnowlegeMode>  models;

    private SharedUtil sharedUtil;
    public TabModel getCurTabModel() {
        return tabModels.get(viewPage.getCurrentItem());
    }

    public HeadLine getCurHeadLine() {
        if(headLines!=null&&headLines.size()>0)
        return curHeadLine==null?headLines.get(0):curHeadLine;
        return  null;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mView = inflater.inflate(R.layout.fragment_knowledge, container, false);
        x.view().inject(this,mView);
        init();
        return mView;
    }

    private void init(){
        sharedUtil = SharedUtil.getInstance(mContext);
        fileCacheManager = new FileCacheManager();
        logic = PositionKnowlegeDataLogic.getInstance(mContext);
        logic.setCallkBack(new PositionKnowlegeDataLogic.SucdessCallkBack() {
            @Override
            public void done(List<PositionKnowlegeMode> mdels) {
                    models=mdels;
                     getHeadLines();
                 setData(headLines);
            }
        });


        initBroadCast();
        initDateDailog();
        tabModels  = TabDateUtil.getDays();

        initHeadLines();

        headLineDailog = new HeadLineDailog(mContext,null);
        headLineDailog.setCallback(new HeadLineDailog.HeadDialogCallback() {
            @Override
            public void done(HeadLine headLine,int position) {
                curHeadLine  = headLine;
                sharedUtil.saveCurHeadLineTypeId(curHeadLine.getTypeId());
                topName.setText(headLine.getTypeName());

                headLines.get(lastPosition).setCheck(false);
                headLines.get(position).setCheck(true);
                headLineDailog.update(headLines);
                lastPosition=position;

                for(Fragment fragment : fragments) {
                    KnowlageItemFragment knowlageItemFragment = (KnowlageItemFragment) fragment;
                    if(headLine.getTypeId().equals(knowlageItemFragment.getTypeId()))
                        continue;
                    knowlageItemFragment.setTypeId(headLine.getTypeId());
                    knowlageItemFragment.refresh();
                }
            }
        });
        initTabLayout(false);
        initHead(mView);
        topName.setText("管理");
        topName.setOnClickListener(this);
        topName.setCompoundDrawablesWithIntrinsicBounds(null,null,getResources().getDrawable(R.mipmap.triangle),null);
        rightIcon.setVisibility(View.GONE);

        leftIcon.setVisibility(View.VISIBLE);
        leftIcon.setImageResource(R.mipmap.calendar);
        leftIcon.setOnClickListener(this);
    }

    /***
     * 初始化广播
     */
    private void initBroadCast() {
        localBroadcastManager = LocalBroadcastManager.getInstance(mContext);
        localBroadCast = new LocalBroadCast(new LocalBroadCast.BroadCastCallBack() {
            @Override
            public void done(Context context, Intent intent) {
                String action = intent.getAction();
                if(action.equals(LocalBroadCast.HEAD_LINE_SORT)){
                    initHeadLines();
                }
            }
        });
        IntentFilter intent = new IntentFilter();
        intent.addAction(LocalBroadCast.HEAD_LINE_SORT);
        localBroadcastManager.registerReceiver(localBroadCast, intent);

        dataChangeBroadCast = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                if (ACTION_DATE_CHANGED.equals(intent.getAction())) {

                }
            }
        };
        mContext.registerReceiver(dataChangeBroadCast, new IntentFilter(ACTION_DATE_CHANGED));
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        localBroadcastManager.unregisterReceiver(localBroadCast);
        mContext.unregisterReceiver(dataChangeBroadCast);
    }

    /***
     * 初始化日期选择器
     */
    private void initDateDailog() {
        Calendar startDate = Calendar.getInstance();
        startDate.set(1970, 0, 1);
        Calendar endDate = new GregorianCalendar();
        Date date = new Date();
        endDate.setTime(date);
        endDate.add(Calendar.DATE, -7);

        //时间选择器 ，自定义布局
        timerPicker = new TimePickerView.Builder(mContext, new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                if(tabModels.get(0).isAdd()){
                    tabModels.remove(0);
                }
               String dt =  TabDateUtil.format(date);
                Calendar cd = Calendar.getInstance();
                cd.setTime(date);
                TabDateUtil.add(tabModels,cd,dt,0);
                tabModels.get(0).setAdd(true);
                initTabLayout(true);
//                tabLayout.updateTab();
            }
        })
        .setDate(endDate)
        .setRangDate(startDate, endDate)
        .setLayoutRes(R.layout.pickerview_custom_time, new CustomListener() {
            @Override
            public void customLayout(View v) {
                final TextView tvSubmit = (TextView) v.findViewById(R.id.tv_finish);
                TextView ivCancel = (TextView) v.findViewById(R.id.iv_cancel);
                tvSubmit.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        timerPicker.returnData();
                        timerPicker.dismiss();
                    }
                });
                ivCancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        timerPicker.dismiss();
                    }
                });
            }
        })
        .setType(new boolean[]{true, true, true, false, false, false})
        .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
        .setDividerColor(getResources().getColor(R.color.gray_deep))
        .build();
    }

    /***
     * 初始化头部导航栏
     */
    private void initHeadLines() {
        Observable.create(new Observable.OnSubscribe<List<PositionKnowlegeMode>>() {
            @Override
            public void call(Subscriber<? super List<PositionKnowlegeMode>> subscriber) {
                try {
                    List<PositionKnowlegeMode> data = (List<PositionKnowlegeMode>) fileCacheManager.readObject(logic.getCachePath());
                    subscriber.onNext(data);
                }catch (Exception e){

                }
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<List<PositionKnowlegeMode>>() {
                    @Override
                    public void onCompleted() {
//                        // 缓存超过10分钟则重新获取数据
//                        if(models == null )//|| System.currentTimeMillis()-skillModel.getCacheTime() > 1000*60*10
//                            getData(id);
                        File file = new File(logic.getCachePath());
                        if(file!=null) {
                            long lastTime = file.lastModified();//缓存最后修改时间
                            String time = TimeUtil.formatData(lastTime);
                            if (models == null || (System.currentTimeMillis() - lastTime) > 1000 * 60 * 5) {
                                logic.getKnowlegeData();
                            }
                        }
                    }
                    @Override
                    public void onError(Throwable e) {
                        onCompleted();
                    }
                    @Override
                    public void onNext(List<PositionKnowlegeMode> data) {
                        try {
                            models = data;
                            if (models == null) {//
                                models = PositionKnowlegeDataLogic.getModels();
                                if (models == null || models.size() == 0) {
                                    logic.getKnowlegeData();
                                } else {
                                    getHeadLines();
                                    setData(headLines);
                                }
                            } else {
                                PositionKnowlegeDataLogic.setModels(models);
                                getHeadLines();
                                setData(headLines);
                            }
                        }catch (Exception e) {

                        }
                        onCompleted();
                    }
                });
    }

    //解析headlines
    private void getHeadLines(){
        if(models!=null){
            headLines = new ArrayList<>();
            for (PositionKnowlegeMode model: models) {
                HeadLine hedLine = new HeadLine();
                hedLine.setTypeName(model.getName());
//                hedLine.setId(model.getId());
                hedLine.setTypeId(model.getNavType());
                headLines.add(hedLine);
            }
        }
    }

    private void setData(List<HeadLine> heads) {
        String curHeadLineId = sharedUtil.getCurHeadlineTypeId();
        if(curHeadLine==null)curHeadLine=heads.get(0);
        if(TextUtils.isEmpty(curHeadLineId))curHeadLineId=curHeadLine.getTypeId();
        for (HeadLine head:heads ) {
                if(head.getTypeId().equals(curHeadLineId)){
                    head.setCheck(true);
                    curHeadLine=head;
                    break;
                }
        }
        headLineDailog.update(heads);
        topName.setText(curHeadLine.getTypeName());
        for(Fragment fragment : fragments) {
            KnowlageItemFragment knowlageItemFragment = (KnowlageItemFragment) fragment;
            if(curHeadLineId.equals(knowlageItemFragment.getTypeId()))
                continue;
            knowlageItemFragment.setTypeId(curHeadLineId);
            knowlageItemFragment.refresh();
        }
    }

    /***
     * 请求获取headline数据
     */
    private void getHeadLine() {
        JsonObject param = new JsonObject();
        param.addProperty("token", HttpHelper.token);
        param.addProperty("type", 12);
        HttpHelper.getInstance(mContext).getHeadLine(param, 0x01, this);
    }

    /***
     * 初始化tab
     */
    private void initTabLayout(boolean first) {
        fragments = new ArrayList<>();
        int size = tabModels.size();

        HeadLine headLine = getCurHeadLine();
        String typeId = headLine == null ? "" : headLine.getTypeId();
        for (int i = 0; i < size; i++) {
            fragments.add(new KnowlageItemFragment().newInstance(typeId, tabModels.get(i).getDate()));
        }
        adpter = new FragMentAdapter(getFragmentManager(),fragments);
        viewPage.setAdapter(adpter);

        tabNames.clear();
        for(TabModel tabModel : tabModels)
            tabNames.add(tabModel.getName());
        tabView.setupWithViewPager(viewPage);
        tabView.setTabItems(tabNames);

        if(first){
            viewPage.setCurrentItem(0);
        }else {
            viewPage.setCurrentItem(size - 2);
        }
    }

    @Override
    public void onStart(int requestType) {
//        loadingDialog.show();
    }

    @Override
    public void onCompleted(int requestType) {

    }

    @Override
    public void onError(int requestType) {
        loadingDialog.cancel();
    }

    @Override
    public void onNext(IModel data, int requestType) {
        loadingDialog.cancel();
        if ( data.getErrcode() == 0) {
            headLines=data.getList(HeadLine.class);
            if (headLines != null && headLines.size() > 0) {
                    headLineDailog.update(headLines);
                    DBHelper.getInstance().delete(HeadLine.class);
                    DBHelper.getInstance().save(headLines);

                setData(headLines);
            }else{
                ToasUtil.toast(mContext,"获取导航失败");
            }

        }
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.module_name:
                headLineDailog.showDialog();
                break;
            case  R.id.icon_left:
                timerPicker.show();
                break;
            default:
                break;
        }
    }
}
